package com.leps.nq.bu.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leps.nq.bu.entity.BuPlc;
import com.leps.nq.bu.entity.BuPump;
import com.leps.nq.bu.entity.BuWell;
import com.leps.nq.bu.mapper.BuPlcMapper;
import com.leps.nq.bu.mapper.BuPumpMapper;
import com.leps.nq.bu.mapper.BuWellMapper;
import com.leps.nq.bu.service.IBuPlcService;
import com.leps.nq.bu.vo.PlcQueryModel;
import com.leps.nq.bu.vo.PlcVo;
import com.leps.nq.common.util.SecurityUtil;
import com.leps.nq.common.vo.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;

/**
 * <p>
 * plc表 服务实现类
 * </p>
 *
 * @author hex
 * @since 2022-05-22
 */
@Service
public class BuPlcServiceImpl extends ServiceImpl<BuPlcMapper, BuPlc> implements IBuPlcService {
    @Autowired
    private BuPlcMapper buPlcMapper;
    @Autowired
    private BuPumpMapper buPumpMapper;
    @Autowired
    private BuWellMapper buWellMapper;

    @Override
    public PageVo<PlcVo> pageByQueryModel(PlcQueryModel queryModel) {
        Page<PlcVo> page = Page.of(queryModel.getPageNum(), queryModel.getPageSize());
        page = this.buPlcMapper.selectByQueryModel(page, queryModel);
        return PageVo.of(page);
    }

    @Override
    @Transactional
    public boolean updateCascade(BuPlc plc) {
        final int plcId = plc.getPlcId();
        final String plcName = plc.getPlcName();
        final BuPlc origin = this.buPlcMapper.selectById(plcId);
        plc.setUpdateBy(SecurityUtil.getUserName());
        plc.setUpdateTime(new Date());
        this.buPlcMapper.updateById(plc);
        this.buPlcMapper.updateRedundantField(plc);
        if (Objects.equals(origin.getPlcName(), plcName) && Objects.equals(origin.getPlcType1(), plc.getPlcType1()) && Objects.equals(origin.getPlcType2(), plc.getPlcType2()))
            return true;
        BuPump pump = new BuPump();
        pump.setPlcName(plcName);
        pump.setPlcType1(plc.getPlcType1());
        pump.setPlcType2(plc.getPlcType2());
        this.buPumpMapper.update(pump, new UpdateWrapper<BuPump>().eq("plc_id", plcId));
        BuWell well = new BuWell();
        well.setPlcName(plcName);
        well.setPlcType1(plc.getPlcType1());
        well.setPlcType2(plc.getPlcType2());
        this.buWellMapper.update(well, new UpdateWrapper<BuWell>().eq("plc_id", plcId));
        return true;
    }

    @Override
    @Transactional
    public boolean saveAndFillRedundiantField(BuPlc plc) {
        plc.setCreateBy(SecurityUtil.getUserName());
        plc.setCreateTime(new Date());
        this.buPlcMapper.insert(plc);
        this.buPlcMapper.updateRedundantField(plc);
        return true;
    }
}
